// pages/order/orderGoing/orderGoing.js
const handler = require("../../../utils/function.js");
var app = getApp(),
  api = require("../../../api.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    reSetMarker: false,
    prices: '',
    km: '',
    is_online_price: '',
    dingshi: "",
    timer: "",
    latitude: '',
    longitude: '',
    markers: [{
      iconPath: "../../../images/driver/icon-30.png",
      id: 0,
      longitude: 108.94,
      latitude: 34.28,
      width: 15,
      height: 27
    }],
    polyline: [{
      points: [{
        longitude: wx.getStorageSync("startAddress").longitude,
        latitude: wx.getStorageSync("startAddress").latitude
      }, {
        longitude: 108.94,
        latitude: wx.getStorageSync("startAddress").latitude
      }],
      color: "#0299de",
      width: 9,
      dottedLine: false,
      arrowLine: true,
    }],
    controls: [{
      id: 0,
      iconPath: '../../../images/user/icon-30.png',
      position: {
        left: 10,
        top: 10,
        width: 50,
        height: 50
      },
      clickable: true
    }],
    longitude: null,
    latitude: null,
    order_no: '',
    clears: 0
  },

  // 修改用户和一键定位位置
  changeIcon: function() {
    const that = this;
    const {
      controls
    } = this.data;
    wx.getSystemInfo({
      success: function success(res) {
        var controlsH = res.windowWidth / 750 * 130; //计算一像素的宽度 res.windowWidth
        var map_height = res.windowHeight - controlsH;
        controls[0] = {
          id: 0,
          iconPath: '../../../images/user/icon-30.png',
          position: {
            top: map_height - 56,
            left: 10,
            width: 50,
            height: 50
          },
          clickable: true
        };
        that.setData({
          winPath: {
            w: res.windowWidth,
            h: res.windowHeight
          },
          map_height,
          controls,
        });
      }
    });
  },
  // 获取位置路线
  getPolyline: function() {
    handler.getPolyline((res) => {
      const polyline = this.data.polyline;
      polyline[0].points = res;
      this.setData({
        polyline
      });
    })
  },
  // 获取当前经纬度
  get_lat_lng: function(callback) {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        console.log(res, '22222222222222')
        var latitude = res.latitude
        var longitude = res.longitude
        var params = latitude + "," + longitude;
        wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/?l&get_poi=1', //根据经纬度转换成具体地址
          data: {
            "key": "EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD",
            "location": params
          },
          method: 'GET',
          success(rs) {
            console.log(rs)
            that.setData({
              now_location: rs.data.result
            })
            callback({
              now_location: rs.data.result.address,
              latitude: latitude,
              longitude: longitude
            })
          }
        })
      },
    })
  },

  // intoPageHandler 页面跳转
  intoPageHandler: function(e) {
    var that = this;
    let is_online_price = this.data.is_online_price;
    wx.showModal({
      title: '提示',
      content: '确定结束进程？',
      success: function(res) {
        if (res.confirm) {
          wx.stopLocationUpdate({
            success: function(res) {
              wx.offLocationChange(function(rs) {
                console.log("结束成功")
              })
            },
            fail: function(res) {
              console.log("结束失败", res)
            }
          })
          if (is_online_price == 1) {
            clearInterval(that.data.dingshi)
            let ss = [{
              latitude: '',
              longitude: ''
            }]
            app.driver_position = ss
          }
          console.log('结束行程结果', that.data.order_no);
          var formid = e.detail.formId;
          that.get_lat_lng((res) => {
            let end_point = res.now_location;
            let latitude = res.latitude;
            let longitude = res.longitude;
            app.request({
              url: api.order.orderend,
              method: 'post',
              data: {
                formid: formid,
                end_point: end_point,
                order_no: e.currentTarget.dataset.order_no,
                longitude: longitude,
                latitude: latitude
              },
              success: function(rs) {
                if (rs.code == 1) {
                  wx.redirectTo({
                    url: e.currentTarget.dataset.skip,
                  })
                } else {
                  wx.showToast({
                    title: rs.msg,
                    icon:'none'
                  })
                }
              }
            })
          })
          app.endReportHeart()
        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    app.request({
      url: api.order.isOnlinePrice,
      method: 'post',
      data: {},
      success: function(res) {
        console.log('是否开始实施计费', res)
        if (res.code == 1) {
          if (res.data.is_online_price == 1) {
            that.startReportHearts()
          }
          that.setData({
            is_online_price: res.data.is_online_price
          })
        }
      }
    })



    console.log('开始行程', options)

    that.setData({
      order_no: options.order_no,
    })
    // 获取优惠券
    if (options.uid) {
      app.shareCouponsMessage(options.uid)
    }
    this.changeIcon();
  },
  // 时间定时器
  timeTask: function() {
    var that = this;
    app.request({
      url: api.real_time.geting,
      method: 'post',
      data: {
        order_no: that.data.order_no,
      },
      success: function(rs) {
        console.log('经纬度', rs.data)
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},
  /**
   * 生命周期函数--监听页面显示
   */
  onUnload: function() {
    let that = this;
    console.log('隐藏页面，Ia---/*-*-/--*/-*/-*')
    clearInterval(that.data.dingshi)
  },
  startReportHearts: function() {
    const that = this
    console.log('执行-------')
    const polyline = this.data.polyline;
    let dingshis = setInterval(() => {
     if (this.reSetMarker && app.driver_position[app.driver_position.length - 1]) {
       var markers = this.data.markers;
        markers[0].latitude = app.driver_position[app.driver_position.length - 1].latitude;
        markers[0].longitude = app.driver_position[app.driver_position.length - 1].longitude;
        this.setData({
          markers
        })
     }
      // console.log(app.driver_position)
      polyline[0].points = app.driver_position;
     
      this.setData({
        longitude: app.longitudes,
        latitude: app.latitudes,
        prices: app.actual_km_price,
        km: app.actual_km,
        polyline
      })

      // m-shit
      app.request({
        url: api.order.getfind,
        method: 'post',
        data: {
          order_no: that.data.order_no,
        },
        success: function(rs) {
          if (rs.code == 1) {
            that.reSetMarker = true;
            that.setData({
              order: rs.data,
              markers: rs.data.slocaltion,
              driver: wx.getStorageSync("driver"),
              longitude: rs.data.elocaltion.lng,
              latitude: rs.data.elocaltion.lat,
              elocation: rs.data.elocaltion,
              slocation: rs.data.slocation.location,
            })
            wx.setStorageSync("startAddress", rs.data.slocation)
            wx.setStorageSync("endAddress", rs.data.elocation)


            // that.getPolyline();
          } else {
            wx.showToast({
              title: rs.msg,
            })
            wx.redirectTo({
              url: '',
            })
            wx.redirectTo({
              url: '../orderedStatus/orderedStatus?order_no=' + that.data.order_no,
            })
          }
        }
      }) 
       
      // m-shit






    }, 2000);
    this.setData({
      dingshi: dingshis,
    })
  },
  onShow: function() {
    var that = this;
    app.request({
      url: api.order.isOnlinePrice,
      method: 'post',
      data: {},
      success: function(res) {
        console.log('是否开始实施计费', res)
        if (res.code == 1) {
          if (res.data.is_online_price == 1) {
            let order_no = that.data.order_no
            app.startReportHeart(order_no)
            console.log('开始行程结果', that.data.order_no);
            app.request({
              url: api.order.getfind,
              method: 'post',
              data: {
                order_no: that.data.order_no,
              },
              success: function(rs) {
                if (rs.code == 1) {
                  that.reSetMarker = true;
                  that.setData({
                    order: rs.data,
                    markers: rs.data.slocaltion,
                    driver: wx.getStorageSync("driver"),
                    longitude: rs.data.elocaltion.lng,
                    latitude: rs.data.elocaltion.lat,
                    elocation: rs.data.elocaltion,
                    slocation: rs.data.slocation.location,
                  })
                  wx.setStorageSync("startAddress", rs.data.slocation)
                  wx.setStorageSync("endAddress", rs.data.elocation)


                  // that.getPolyline();
                } else {
                  wx.showToast({
                    title: rs.msg,
                  })
                  wx.redirectTo({
                    url: '',
                  })
                  wx.redirectTo({
                    url: '../orderedStatus/orderedStatus?order_no=' + that.data.order_no,
                  })
                }
              }
            })
          
          } else {
            console.log('开始行程结果', that.data.order_no);
            app.request({
              url: api.order.getfind,
              method: 'post',
              data: {
                order_no: that.data.order_no,
              },
              success: function(rs) {
                if (rs.code == 1) {
                  that.setData({
                    order: rs.data,
                    markers: rs.data.slocaltion,
                    driver: wx.getStorageSync("driver"),
                    longitude: rs.data.elocaltion.lng,
                    latitude: rs.data.elocaltion.lat,
                    elocation: rs.data.elocaltion,
                    slocation: rs.data.slocation.location,
                  })
                  wx.setStorageSync("startAddress", rs.data.slocation)
                  wx.setStorageSync("endAddress", rs.data.elocation)


                  that.getPolyline();
                } else {
                  wx.showToast({
                    title: rs.msg,
                  })
                  wx.redirectTo({
                    url: '',
                  })
                  wx.redirectTo({
                    url: '../orderedStatus/orderedStatus?order_no=' + that.data.order_no,
                  })
                }
              }
            })
          }

        }
      }
    })


    // 修改地图高
    this.changeMapHeight()
  },
  changeMapHeight: function() {
    let that = this;
    wx.getSystemInfo({
      success: function success(res) {
        console.log(res, '22222222222222222222')
        var controlsH = res.windowWidth / 750 * 110; //计算一像素的宽度 res.windowWidth
        var map_height = res.windowHeight - controlsH;
        var controls = [{
          id: 1,
          iconPath: '../../../images/driver/icon-50.png',
          position: {
            left: 10,
            top: map_height - 70,
            width: 50,
            height: 50
          },
          clickable: true
        }, {
          id: 2,
          iconPath: '../../../images/driver/end.png',
          position: {
            left: 10,
            top: map_height - 126,
            width: 50,
            height: 50
          },
          clickable: true
        }];
        that.setData({
          winPath: {
            w: res.windowWidth,
            h: res.windowHeight
          },
          map_height,
          controls: controls
        });
      }
    });
  },
  // 一键定位
  controltap(e) {
    if (e.controlId == 1) {
      this.getAddress()
      return
    }
    if (e.controlId == 2) {
      this.startHandler()
      return
    }
    let that = this;
    console.log("map controltap", e.controlId)
    const addresses = wx.getLocation({
      type: 'gcj02',
      success(res) {
        console.log(res)
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
        })

      }
    })
  },
  // 获取当前位置
  getAddress: function() {
    let that = this;
    wx.getLocation({
      success: function(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        })
      },
    })
  },
  // 跳转起点
  startHandler: function() {
    let elocation = this.data.elocation;
    if (elocation.lat && elocation.lng) {
      wx.openLocation({
        latitude: elocation.lat,
        longitude: elocation.lng,
      })
    }
  },
  // 用户分享
  onShareAppMessage: function() {
    let title = app.shareAppMessage().title;
    let imageUrl = app.shareAppMessage().imageUrl;
    let desc = app.shareAppMessage().desc;
    let path = app.shareAppMessage().path;
    console.log(app.shareAppMessage())
    return {
      title: title,
      imageUrl: imageUrl,
      desc: desc,
      path: path,
    }
  },
})